package com.huping.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.huping.mapper.*;
import com.huping.pojo.*;
import com.huping.service.GradeService;
import com.huping.utils.hupingAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service
public class GradeServiceImpl implements GradeService {
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private GradeMapper gradeMapper;
    @Autowired
    private HomeworkMapper homeworkMapper;
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private ScoreRecordMapper scoreRecordMapper;

    private static int rotate = 0;

    public Result getAllStudentsHomeworkByHomeworkId(String userid, JSONObject param) {

        Integer homeworkId = Integer.parseInt(param.getString("homeworkId"));
        Homework homework = homeworkMapper.getHomeworkDetail(homeworkId);
        if (homework == null) {
            return Result.error("教师未发布此作业");
        }
        List<Student> students = studentMapper.getStudentsByCourseId(homework.getCourseId(), userid);
        //grade表里没有的grade插入进去
        for (Student student : students) {
            if (gradeMapper.checkGradeExist(new Grade(null,
                    student.getStudentId(),
                    homeworkId,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null
            )) < 1) {

                gradeMapper.gradeInsert(student.getStudentId(), homeworkId);
            }

        }

        PageHelper.startPage(Integer.parseInt(param.getString("page")), Integer.parseInt(param.getString("size")));
        List<Map<String, Object>> r = teacherMapper.getAllStudentsHomeworkByHomeworkId(homeworkId);

        String jsonStr = JSON.toJSONString(r);

        Page<Map<String, Object>> p = (Page<Map<String, Object>>) r;
        PageBean pageBean = new PageBean(p.getTotal(), p.getResult());

        JSONObject pageBeanJSON = (JSONObject) JSONObject.toJSON(pageBean);

        for (int i = 0; i < p.size(); i++) {
            String fileString = pageBeanJSON.getJSONArray("rows").getJSONObject(i).getString("file");
            JSONArray filesArray = JSON.parseArray(fileString);
            pageBeanJSON.getJSONArray("rows").getJSONObject(i).put("file", filesArray);
        }

        return Result.success(pageBeanJSON);

    }


    public Result teacherGiveStudentGrade(Integer homeworkId, String studentId, Integer score, String comment) {

        gradeMapper.teacherUpdateStudentScore(homeworkId, studentId, score, comment);
        return Result.success("打分成功");


    }


    public Result studentGetHupingHomework(String userid, JSONObject param) {//学生互评获得新的分配
        Integer homeworkId = Integer.parseInt(param.getString("homeworkId"));
        //先在grade里插入
        Homework homework = homeworkMapper.getHomeworkDetail(homeworkId);
        List<Student> students = studentMapper.getStudentsByCourseId(homework.getCourseId(), homework.getTeacherId());
        //grade表里没有的grade插入进去
        for (Student student : students) {
            if (gradeMapper.checkGradeExist(new Grade(null,
                    student.getStudentId(),
                    homeworkId,
                    null,
                    "[]",
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null
            )) < 1) {

                gradeMapper.gradeInsert(student.getStudentId(), homeworkId);
            }

        }


        if (homeworkMapper.getMethod(homeworkId).equals("1")) {
            int newSequence1;
            int originSequence1;
            if (gradeMapper.CheckScoreTeacherNullExist(homeworkId) > 0) {
                return Result.error("等待教师全部评阅");
            }

            List<Map<String, Object>> list = gradeMapper.getAllScoreTeacher(homeworkId);


            List<Map<String, Object>> newList = hupingAlgorithm.getRankList(list);

            for (Map<String, Object> map : newList) {

                gradeMapper.setRank(homework.getHomeworkId(), (String) map.get("studentId"), (String) map.get("rankValue"));


            }
            int partFull = 0;
            do {
                String rank = String.valueOf(rotate % 3);
                List<Map<String, Object>> list1 = gradeMapper.getHupingStudentHomeworkByRank(rank, userid);


                for (Map<String, Object> map : list1) {

                    if (scoreRecordMapper.checkScoreRecordExist(userid, homeworkId, (String) map.get("studentId")) >= 1)
                        continue;


                    if (scoreRecordMapper.getSequence(userid, homeworkId) == null) {
                        originSequence1 = 0;
                    } else {
                        originSequence1 = scoreRecordMapper.getSequence(userid, homeworkId);
                    }
                    newSequence1 = originSequence1 + 1;
                    scoreRecordMapper.insertScoreRecord(homeworkId, userid, (String) map.get("studentId"), newSequence1);


                    JSONObject listJSON = (JSONObject) JSONObject.toJSON(map);
                    JSONArray filesArray = JSON.parseArray((String) map.get("file"));
                    listJSON.put("file", filesArray);
                    rotate++;
                    return Result.success(listJSON);

                }
                rotate++;
                partFull++;
            } while (partFull != 3);


            return Result.error("全部阅览完毕");
        }

        Map<String, Object> list;
        int r = 0;
        int newSequence;
        int originSequence;
        String skip = "0";
        String receiver_id;
        do {
            list = gradeMapper.getHupingStudentHomeworkByOrder(userid, Integer.parseInt(param.getString("homeworkId")), Integer.parseInt(skip));


            receiver_id = (String) list.get("studentId");
            skip = String.valueOf(Integer.parseInt(skip) + 1);
            if (skip.equals(String.valueOf(students.size() - 1)))
                break;

        } while (scoreRecordMapper.checkScoreRecordExist(userid, homeworkId, receiver_id) >= 1);


        if (scoreRecordMapper.checkScoreRecordExist(userid, homeworkId, receiver_id) < 1) {
            if (scoreRecordMapper.getSequence(userid, homeworkId) == null) {
                originSequence = 0;
            } else {
                originSequence = scoreRecordMapper.getSequence(userid, homeworkId);
            }
            newSequence = originSequence + 1;
            scoreRecordMapper.insertScoreRecord(homeworkId, userid, receiver_id, newSequence);

            //插入后要修改numbers记录
            gradeMapper.updateNumbersInGrade(String.valueOf(newSequence), (String) list.get("studentId"), homeworkId);


            JSONObject listJSON = (JSONObject) JSONObject.toJSON(list);
            JSONArray filesArray = JSON.parseArray((String) list.get("file"));
            listJSON.put("file", filesArray);
            return Result.success(listJSON);
        }

        return Result.error("已全部阅览");


    }

    public Result getHomeworkBySequence(String userid, JSONObject param) {
        Map<String, Object> result =scoreRecordMapper.getHomeworkBySequence(userid, Integer.parseInt(param.getString("sequence")), Integer.parseInt(param.getString("homeworkId")));

        JSONObject resultJSON = (JSONObject) JSONObject.toJSON(result);
        JSONArray filesArray = JSON.parseArray((String) result.get("file"));
        resultJSON.put("file", filesArray);
        return Result.success(resultJSON);


    }

    public Result updateHupingScoreInScoreRecord(String userid, JSONObject param) {
        int score;
        try {
            score = Integer.parseInt(param.getString("score"));
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return Result.error("请输入正确的分数");
        }
        String receiverId = param.getString("receiverId");
        Date gradeTime = param.getDate("gradeTime");

        Integer homeworkId = Integer.parseInt(param.getString("homeworkId"));
        String comment=param.getString("comment");
        int r = scoreRecordMapper.updateHupingScore(score, gradeTime, userid, receiverId, homeworkId,comment);
        if (r == 1)
            return Result.success("互评成绩更新成功");
        return Result.error("互评成绩更新失败");
    }

    public PageBean selectHistoricalReading(String userid, JSONObject param) {
        Integer homeworkId = Integer.parseInt(param.getString("homeworkId"));
        PageHelper.startPage(Integer.parseInt(param.getString("page")), Integer.parseInt(param.getString("size")));
        List<Map<String, Object>> r = scoreRecordMapper.selectHistricalReading(userid, homeworkId);
        Page<Map<String, Object>> p = (Page<Map<String, Object>>) r;
        PageBean pageBean = new PageBean(p.getTotal(), p.getResult());
        return pageBean;

    }

    public Result getGradeStatistic(JSONObject param) {

        Integer homeworkId = Integer.parseInt(param.getString("homeworkId"));
        return Result.success(new Statisitc(
                gradeMapper.getGradeStatisticA(homeworkId),
                gradeMapper.getGradeStatisticB(homeworkId),
                gradeMapper.getGradeStatisticC(homeworkId),
                gradeMapper.getGradeStatisticD(homeworkId),
                gradeMapper.getGradeStatisticNotSubmit(homeworkId),
                gradeMapper.getGradeStatisticSubmit(homeworkId)

        ));
    }

    public Result getExcellentHomework(JSONObject param) {
        Integer homeworkId = Integer.parseInt(param.getString("homeworkId"));

        PageHelper.startPage(Integer.parseInt(param.getString("page")), Integer.parseInt(param.getString("size")));
        List<Map<String, Object>> r = gradeMapper.getExcellentHomework(homeworkId);
        Page<Map<String, Object>> p = (Page<Map<String, Object>>) r;
        PageBean pageBean = new PageBean(p.getTotal(), p.getResult());
        JSONObject pageBeanJSON = (JSONObject) JSONObject.toJSON(pageBean);
        for (int i = 0; i < p.getTotal(); i++) {
            String fileString = pageBeanJSON.getJSONArray("rows").getJSONObject(i).getString("file");
            JSONArray filesArray = JSON.parseArray(fileString);
            pageBeanJSON.getJSONArray("rows").getJSONObject(i).put("file", filesArray);
        }
        return Result.success(pageBeanJSON);


    }

    public Result setExcellentHomework(JSONObject param) {
        Integer homeworkId = Integer.parseInt(param.getString("homeworkId"));
        String studentId = param.getString("studentId");
        String excellent=param.getString("excellent");
        Homework homework = homeworkMapper.getHomeworkDetail(homeworkId);
        if (homework == null) {
            return Result.error("无此作业");
        }

        gradeMapper.updateExcellent(homeworkId, studentId,excellent);

        return Result.success("设置成功");
    }

    public Result getNotSubmit(JSONObject param) {
        Integer homeworkId = Integer.parseInt(param.getString("homeworkId"));
        PageHelper.startPage(Integer.parseInt(param.getString("page")), Integer.parseInt(param.getString("size")));
        List<Map<String, Object>> r = gradeMapper.getNotSubmit(homeworkId);
        Page<Map<String, Object>> p = (Page<Map<String, Object>>) r;
        PageBean pageBean = new PageBean(p.getTotal(), p.getResult());
        return Result.success(pageBean);


    }

    public Map<String, Object> getTotal(String userid, JSONObject param) {
        Integer homeworkId = Integer.parseInt(param.getString("homeworkId"));
        int scoreTeacher = gradeMapper.getStudentScoreTeacher(userid, homeworkId);

        List<Map<String, Object>> list = scoreRecordMapper.getAllScoreRecord(userid, homeworkId);

        List<Integer> newList = new ArrayList<>();
        for (Map<String, Object> map : list) {
            newList.add((Integer) map.get("score"));
        }
        Integer[] hupingArrInteger = newList.toArray(new Integer[0]);
        int[] hupingArray = new int[hupingArrInteger.length];

        for (int i = 0; i < hupingArrInteger.length; i++) {
            hupingArray[i] = hupingArrInteger[i]; // 自动拆箱
        }

        int scoreHuping = hupingAlgorithm.getScoreHuping(hupingArray);
        gradeMapper.setScoreHuping(userid, homeworkId, scoreHuping);
        Integer scoreTotal = (int) (scoreHuping * 0.3 + scoreTeacher * 0.7);
        gradeMapper.setScoreTotal(userid, homeworkId, scoreTotal);
        return gradeMapper.getTotal(userid, homeworkId);

    }

    public Result setMethod(JSONObject param) {
        homeworkMapper.setMethod(Integer.parseInt(param.getString("homeworkId")), param.getString("method"));

        return Result.success("设置成功");
    }

    public Result getTotalNumber(String userid,JSONObject param){

        int number;
        if( scoreRecordMapper.getSequence(userid,Integer.parseInt(param.getString("homeworkId")))==null){
            number=0;
            return Result.success(number);
        }

        number=scoreRecordMapper.getSequence(userid,Integer.parseInt(param.getString("homeworkId")));
        return Result.success(number);
    }


}
